package com.aurora.advanced;

import org.apache.commons.lang3.StringUtils;
import org.apache.flink.streaming.connectors.elasticsearch7.RestClientFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.NodeSelector;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

/**
 * 描述：设置用于创建 Elasticsearch REST 客户端的工厂
 * 解释：可以自定义创建 Elasticsearch REST 客户端的逻辑，实现 ElasticsearchSinkBase.RestClientFactory 接口
 *
 * @author 浅夏的猫
 * @version 1.0.0
 * @date 2024-02-13 00:12:15
 */
public class CustomRestClientFactory implements RestClientFactory {

    private ElasticsearchEntity elasticsearchEntity;

    public CustomRestClientFactory(ElasticsearchEntity elasticsearchEntity) {
        this.elasticsearchEntity = elasticsearchEntity;
    }

    /**
     * 描述：es请求参数配置
     *
     * @param restClientBuilder 参数建造器
     */
    @Override
    public void configureRestClientBuilder(RestClientBuilder restClientBuilder) {

        //设置默认的 HTTP 头部信息，这些信息将在每个请求中包含
        Header contentType = new BasicHeader("Content-Type", "application/json");
        Header authorization = new BasicHeader("Authorization", "Bearer your_access_token");
        Header[] headers = {contentType, authorization};
        restClientBuilder.setDefaultHeaders(headers);


        //设置用于监听节点故障的监听器。当节点发生故障时，可以执行特定的操作
        restClientBuilder.setFailureListener(new RestClient.FailureListener());

        //配置用于选择与之通信的节点的策略。这涉及到 Elasticsearch 集群中多个节点的选择。
        restClientBuilder.setNodeSelector(NodeSelector.ANY);

        //为每个请求设置路径前缀。这可以用于将请求定向到特定的子路径。
        if(StringUtils.isNoneBlank(elasticsearchEntity.getPathPrefix())){
            restClientBuilder.setPathPrefix(elasticsearchEntity.getPathPrefix());
        }

        //允许在创建每个请求的时候进行额外的请求配置。
        restClientBuilder.setRequestConfigCallback(new CustomRequestConfigCallback(elasticsearchEntity));
        //允许在创建 CloseableHttpClient 实例时进行额外的 HTTP 客户端配置。
        restClientBuilder.setHttpClientConfigCallback(new CustomHttpClientConfigCallback(elasticsearchEntity));
        //设置是否启用严格的废弃模式，用于警告有关已弃用功能的使用。
        restClientBuilder.setStrictDeprecationMode(false);
    }
}
